<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-01 15:35:09
 * @LastEditTime: 2020-03-23 23:30:15
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0,viewport-fit=cover" />
	<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
	<title>Hello APP</title>
	<link rel="stylesheet" type="text/css" href="../css/vant.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css" />
	<script type="text/javascript" src="../script/jquery.js"></script>
	<script type="text/javascript" src="../script/vue.min.js"></script>
	<script type="text/javascript" src="../script/vant.min.js"></script>
	<script type="text/javascript" src="../script/fastclick.js"></script>
	<script type="text/javascript" src="../script/base.js"></script>
	<script type="text/javascript" src="../script/db.js"></script>
	<script type="text/javascript" src="../script/jquery.signalR-2.4.1.min.js"></script>
	<script type="text/javascript" src="http://106.15.33.39:9981/signalr/hubs"></script>
	<script type="text/javascript" src="../script/signalr-mediate.js"></script>
	<style type="text/css">
		body {
			background: #efefef;
		}

		.body-no-head {
			height: calc(100% - 50px);
			position: relative;
		}

		.van-info {
			border: 1px solid #f44;
		}
	</style>
</head>

<body>
	<div id="app" v-cloak>
		<div class="init-full">
			<div class="body-no-head">

			</div>
			<van-tabbar inactive-color="#ffffff" active-color="#cd1b21" v-model="tabbarActive" @change="changeTabbar">
				<van-tabbar-item icon="home-o">主页</van-tabbar-item>
				<van-tabbar-item icon="chat-o" :info="dot || ''">消息</van-tabbar-item>
				<van-tabbar-item class="center-add">
					<div class="add">
						<img src="../image/add.png" />
					</div>
				</van-tabbar-item>
				<van-tabbar-item icon="apps-o">栏目</van-tabbar-item>
				<van-tabbar-item icon="user-o">我的</van-tabbar-item>
			</van-tabbar>
		</div>
	</div>
</body>
<script type="text/javascript">
	var vm;
	apiready = function () {

		var mine;
		var isOpenChatList = false;

		var friend = '';
		var groups = '';

		// window.localStorage.removeItem('chatPersonList')

		// DB.dropTable()

		FLD.exitApp();

		api.addEventListener({
			name: 'setUnRedMsg'
		}, function (ret, err) {
			vm.dot = ret.value.dot;
		});

		api.addEventListener({
			name: 'getUnReadMsgRepeat'
		}, function (ret, err) {
			FLD.ajax('getGroupList', {}, function (res) {
				groups = [];
				for (var i = 0; i < res.ds.length; i++) {
					groups.push({
						groupname: res.ds[i].GroupName,
						id: res.ds[i].GroupID.toString(),
						avatar: "../image/group.png" //群组头像
					})
				}
				vm.getUnReadMsg();
			})
		});



		api.addEventListener({
			name: 'openChatList'
		}, function (ret, err) {
			isOpenChatList = ret.value.isOpenChatList;
		});

		api.addEventListener({
			name: 'sendMineMsg'
		}, function (ret, err) {
			var msgObj = ret.value.msgObj;

			var sendmsg = function () {
				if (msgObj.type == 'friend') {
					$.signalrApi.server.chatMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
				else {
					$.signalrApi.server.groupMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
			}



			try {
				$.signalrApi.server.clientLive();
				sendmsg();
			} catch (e) {
				$.signalrApi.start(function () {
					var userInfo = FLD.getUserInfo();
					$.signalrApi.server.clientConnect(userInfo.UserID);
					setTimeout(function () {
						sendmsg();
					}, 500)
				});
			}


		});

		var ajpush = api.require('ajpush');

		ajpush.setBadge({
			badge: 0
		});

		function listenJPush() {
			var ListenerType = '';
			if (api.systemType == "android") {
				ListenerType = 'appintent';
				ajpush.init(function (ret) {
					var param = { alias: FLD.getUserInfo().UserID };
					ajpush.bindAliasAndTags(param, function (ret) {
						
					});
				});
			} else if (api.systemType == "ios") {
				ListenerType = 'noticeclicked';
				var param = { alias: FLD.getUserInfo().UserID };
				ajpush.bindAliasAndTags(param, function (ret) {
					
				});
			}

			api.addEventListener({ name: ListenerType }, function (ret, err) {
				
				if (api.systemType == "android") {
					var data = ret.appParam.ajpush.extra.data;
					if (data) {
						var data_json = JSON.parse(data);
						if (data_json.type == 'chatmsg') {
							FLD.ajax('getInfoByID', { msgID: data_json.msg, type: 1 }, function (res) {
								var row = {
									id: res.ds[0].UserID.toString(),
									groupname: '',
									username: res.ds[0].UserName,
									avatar: res.ds[0].HeadImg,
									type: 'friend'
								}
								api.openWin({
									name: 'chatListDetail',
									url: 'chat/chatListDetail.html',
									reload: true,
									slidBackEnabled: false,
									pageParam: {
										row: row
									}
								})
							})
						} else if (data_json.type == 'groupmsg') {
							FLD.ajax('getInfoByID', { msgID: data_json.msg, type: 2 }, function (res) {
								var row = {
									id: res.ds[0].GroupID.toString(),
									groupname: res.ds[0].GroupName,
									username: '',
									avatar: '../../image/ql.png',
									type: 'group'
								}
								api.openWin({
									name: 'chatListDetail',
									url: 'chat/chatListDetail.html',
									reload: true,
									slidBackEnabled: false,
									pageParam: {
										row: row
									}
								})
							})
						} else if (data_json.type == 'dk') {
							api.openWin({
								name: 'clock',
								url: 'oa/clock.html',
								reload: true,
								slidBackEnabled: false,
								pageParam: {
									row: row
								}
							})
						}
					} else {
						api.openWin({
							name: '历史单据',
							url: 'common/historicalDocuments.html',
							reload: true,
							slidBackEnabled: false,
							pageParam: {
								type: 101,
								tabActive: 0
							}
						})
					}

				} else {
					var data = ret.value.extras.data;

					if (data) {
						var data_json = JSON.parse(data);
						if (data_json.type == 'chatmsg') {
							FLD.ajax('getInfoByID', { msgID: data_json.msg, type: 1 }, function (res) {
								var row = {
									id: res.ds[0].UserID.toString(),
									groupname: '',
									username: res.ds[0].UserName,
									avatar: res.ds[0].HeadImg,
									type: 'friend'
								}
								api.openWin({
									name: 'chatListDetail',
									url: 'chat/chatListDetail.html',
									reload: true,
									slidBackEnabled: false,
									pageParam: {
										row: row
									}
								})
							})
						} else if (data_json.type == 'groupmsg') {
							FLD.ajax('getInfoByID', { msgID: data_json.msg, type: 2 }, function (res) {
								var row = {
									id: res.ds[0].GroupID.toString(),
									groupname: res.ds[0].GroupName,
									username: '',
									avatar: '../../image/ql.png',
									type: 'group'
								}
								api.openWin({
									name: 'chatListDetail',
									url: 'chat/chatListDetail.html',
									reload: true,
									slidBackEnabled: false,
									pageParam: {
										row: row
									}
								})
							})
						} else if (data_json.type == 'dk') {
							api.openWin({
								name: 'clock',
								url: 'oa/clock.html',
								reload: true,
								slidBackEnabled: false,
								pageParam: {
									row: row
								}
							})
						}
					} else {
						api.openWin({
							name: '历史单据',
							url: 'common/historicalDocuments.html',
							reload: true,
							slidBackEnabled: false,
							pageParam: {
								type: 101,
								tabActive: 0
							}
						})
					}


				}

			})
		}

		listenJPush();


		var recMp3 = api.require('recMp3');
		var audioStreamer = api.require('audioStreamer');

		$.clientCallBacks = {};
		var signalRHelper = function () {
			$.signalrApi({
				serverUrl: "http://" + FLD.serverIP,
				clientHub: "IMHub",
				clientEvents: [
					{
						name: "onClientConnect",
						method: function (data) {
							$.clientCallBacks["onClientConnect"](data);
						}
					},
					{
						name: "onChatMsg",
						method: function (userId, msg, timestap) {
							$.clientCallBacks["onChatMsg"](userId, msg, timestap);
						}
					},
					{
						name: "onGroupMsg",
						method: function (userId, groupId, msg, timestap) {
							$.clientCallBacks["onGroupMsg"](userId, groupId, msg, timestap);
						}
					},
					{
						name: "onUserOnlineNotify",
						method: function (userInfo) {
							$.clientCallBacks["onUserOnlineNotify"](userInfo);
						}
					},
					{
						name: "onUserOfflineNotify",
						method: function (userId) {
							$.clientCallBacks["onUserOfflineNotify"](userId);
						}
					}
				]
			});
			//socket连接
			function signalrConnect() {
				$.signalrApi.start(function () {
					var userInfo = FLD.getUserInfo();
					$.signalrApi.server.clientConnect(userInfo.UserID);
				});
			}
			signalrConnect();

			setInterval(function () {

				try {
					$.signalrApi.server.clientLive();
				} catch (e) {
					$.signalrApi.start(function () {
						var userInfo = FLD.getUserInfo();
						$.signalrApi.server.clientConnect(userInfo.UserID);
					});
				}

			}, 2000);
		}






		vm = new Vue({
			el: '#app',
			data: {
				showLoading: false,
				tabbarActive: 0,
				dot: 0
			},
			created: function () {
				var that = this;
				that.getBillRole();
				if (api.safeArea.bottom) {
					setTimeout(function () {
						$('.van-tabbar').css({
							'height': 50 + api.safeArea.bottom + 'px',
							'padding-bottom': api.safeArea.bottom + 'px'
						})
						$('.body-no-head').css({
							'height': 'calc(100% - ' + (50 + api.safeArea.bottom) + 'px)'
						})
					}, 300)

				}
				that.getUserInfo();

				that.initChat();
				if (FLD.getUserInfo().S_Type == 1) {
					api.openFrame({
						name: 'index',
						url: './index.html',
						rect: {
							x: 0,
							y: 0,
							w: api.winWidth,
							h: api.winHeight - 61 - api.safeArea.bottom
						}
					});
				} else {
					api.openFrame({
						name: 'index',
						url: './index_yw.html',
						rect: {
							x: 0,
							y: 0,
							w: api.winWidth,
							h: api.winHeight - 61 - api.safeArea.bottom
						}
					});
				}

				that.checkNewAPP();
			},
			methods: {
				checkNewAPP() {
					var that = this;
					var mam = api.require('mam');
					mam.checkUpdate(function (ret, err) {
						if (ret) {
							
							if (ret.result.update) {
								api.openFrame({
									name: 'updateAPP',
									url: 'common/updateAPP.html',
									bgColor: 'rgba(255,255,255,0)',
									rect: {
										x: 0,
										y: 0,
										w: api.winWidth,
										h: api.winHeight
									},
									pageParam: {
										updateData: ret.result
									}
								});
							}
						}
						that.openAgreement();
					});
				},
				initChat() {
					var that = this;
					FLD.ajax('GetChatUser', {}, function (res) {
						userData = res.ds[0];
						mine = {
							username: res.ds[0].UserName,
							id: res.ds[0].UserID.toString(),
							status: "online",
							sign: res.ds[0].Sign,
							avatar: res.ds[0].HeadImg
						}
						var friendInfo = [{
							"groupname": "福路德用户",
							id: 1
						}];

						groups = [];
						friend = [];
						//用户列表
						for (var i = 0; i < res.ds1.length; i++) {
							friend.push({
								username: res.ds1[i].UserName,
								id: res.ds1[i].UserID.toString(),
								status: res.ds1[i].ContextIDs ? "online" : 'offline',
								sign: res.ds1[i].Sign,
								avatar: res.ds1[i].HeadImg,
								contextIDs: res.ds1[i].ContextIDs
							})
						}
						//群列表
						for (var i = 0; i < res.ds2.length; i++) {
							groups.push({
								groupname: res.ds2[i].GroupName,
								id: res.ds2[i].GroupID.toString(),
								avatar: "../../image/ql.png" //群组头像
							})
						}

						friendInfo[0].list = friend;

						$.clientCallBacks["onClientConnect"] = (contextID) => {
							mine["contextIDs"] = contextID;
						}
						$.clientCallBacks["onChatMsg"] = (userId, msg, timestamp) => {
							let fs = friend.filter(item => item.id == userId);
							if (fs.length > 0) {
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend", //聊天窗口来源类型，从发送消息传递的to里面获取
									content: msg,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								}
								api.sendEvent({
									name: 'getChatMsg',
									extra: {
										msgObj: msgObj
									}
								});
								if (isOpenChatList) {
									api.sendEvent({
										name: 'checkChatList',
										extra: {
											msgObjArray: [msgObj]
										}
									});

								} else {
									that.setChatStorage([msgObj]);
									if (msg) {
										that.dot++;
									}

								}


								if (msg) {

									audioStreamer.onNormal();
									audioStreamer.openPlayer({
										path: 'widget://image/chat/msg.mp3',
									}, function (ret) {

									});
								}

							}
						}
						$.clientCallBacks["onGroupMsg"] = (userId, groupId, msg, timestamp) => {

							var getGroupList = function () {
								FLD.ajax('getGroupList', {}, function (res) {
									groups = [];
									for (var i = 0; i < res.ds.length; i++) {
										groups.push({
											groupname: res.ds[i].GroupName,
											id: res.ds[i].GroupID.toString(),
											avatar: "../../image/ql.png" //群组头像
										})
									}
									onGroupMsgGet();
								})
							}

							var onGroupMsgGet = function () {
								var fs = friend.filter(item => item.id == userId);

								var gs = groups.filter(item => item.id == groupId);
								if (gs.length == 0) {
									getGroupList();
								}
								if (fs.length > 0) {
									//接收消息
									var msgObj = {
										groupname: gs[0].groupname,
										username: fs[0].username,
										avatar: fs[0].avatar,
										id: groupId,
										type: "group", //聊天窗口来源类型，从发送消息传递的to里面获取
										content: msg,
										cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
										mine: false,  //是否我发送的消息，如果为true，则会显示在右方
										fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
										timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
									};


									api.sendEvent({
										name: 'getChatMsg',
										extra: {
											msgObj: msgObj
										}
									});

									if (isOpenChatList) {
										api.sendEvent({
											name: 'checkChatList',
											extra: {
												msgObjArray: [msgObj]
											}
										});
									} else {
										that.setChatStorage([msgObj]);
										if (msg) {
											that.dot++;
										}
									}


								}
							}

							onGroupMsgGet();
							if (msg) {
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}



						}


						$.clientCallBacks["onUserOnlineNotify"] = (info) => {

						}

						$.clientCallBacks["onUserOfflineNotify"] = (userId) => {

						}

						signalRHelper();
						//获取未读信息
						setTimeout(function () {
							that.getUnReadMsg();
						}, 2000);
					})
				},
				setChatStorage(msgObjArray) {
					var that = this;
					var sql = "select * from Chat where UserID='" + FLD.getUserInfo().UserID + "'";
					var chatPersonList_sql = DB.selectSqlSync(sql);
					if (chatPersonList_sql.length) {
						var chatPersonList = JSON.parse(chatPersonList_sql[0].JSONStr1);
						for (var i in msgObjArray) {
							if (msgObjArray[i].content) {
								if (msgObjArray[i].type == 'group') {
									msgObjArray[i].avatar = '../../image/ql.png';
								}
								var x = 0;
								for (var j in chatPersonList) {
									if (parseInt(chatPersonList[j].id) == parseInt(msgObjArray[i].id) && chatPersonList[j].type == msgObjArray[i].type) {
										x = 1;
										msgObjArray[i].unReadNum = (parseInt(chatPersonList[j].unReadNum) || 0) + 1;
										chatPersonList[j] = msgObjArray[i];
									}
								}
								if (x == 0) {
									msgObjArray[i].unReadNum = 1;
									chatPersonList.unshift(msgObjArray[i]);
								}
							}

						}

						var sql = "update Chat set JSONStr1='" + JSON.stringify(chatPersonList).replace(/\'/g, '\'\'') + "',UpdateTime='" + FLD.getFormatDate() + "' where ChatID='" + chatPersonList_sql[0].ChatID + "'";
						DB.executeSql(sql, function () {

						})

					} else {
						var sql = "insert into Chat (UserID,JSONStr1,CreateTime) values ('" + FLD.getUserInfo().UserID + "','" + JSON.stringify(msgObjArray).replace(/\'/g, '\'\'') + "','" + FLD.getFormatDate() + "')"
						DB.executeSql(sql, function () {

						})
					}
				},
				getUnReadMsg() {
					var that = this;
					FLD.ajax('getUnReadMsg', {}, function (res) {
						var unReadMsgObj = [];
						for (var i = 0; i < res.ds.length; i++) {
							//每条消息重新发送给当前用户
							var fs = friend.filter(function (item) {
								return item.id == res.ds[i].FromUserID;
							})
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds[i].Content,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}
						for (var i = 0; i < res.ds1.length; i++) {
							var fs = friend.filter(function (item) {
								return item.id == res.ds1[i].FromUserID;
							})
							var gs = groups.filter(function (item) {
								return item.id == res.ds1[i].GroupID;
							});
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: gs[0].groupname,
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: res.ds1[i].GroupID,
									type: "group",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds1[i].Content,
									cid: 0, //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds1[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}

						if (isOpenChatList) {
							api.sendEvent({
								name: 'checkChatList',
								extra: {
									msgObjArray: unReadMsgObj
								}
							});
						} else {
							if (unReadMsgObj.length) {
								that.dot = unReadMsgObj.length;
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}
						}

					})
				},
				getBillRole() {
					FLD.ajax('getMainMenuByUser', {}, function (res) {
						window.localStorage.setItem('billRole', JSON.stringify(res.ds2));
					})
				},
				openAgreement() {
					if (!window.localStorage.getItem('ifAggreAgreement')) {
						api.openFrame({
							name: 'agreement',
							url: 'common/agreement.html',
							bgColor: 'rgba(255,255,255,0)',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight
							}
						});
					}
				},
				getUserInfo() {
					var that = this;
					FLD.ajax('AP_GetUserNM', {}, function (res) {
						res.ds[0].isRemb = FLD.getUserInfo().isRemb;
						window.localStorage.setItem('userInfo', JSON.stringify(res.ds[0]));
					})
				},
				changeTabbar(index) {
					var url = '';
					if (index == 0) {
						if (FLD.getUserInfo().S_Type == 1) {
							url = 'index';
						} else {
							url = 'index_yw';
						}

					} else if (index == 1) {
						url = 'chat/chatList';
						this.tabbarActive = -1;
					} else if (index == 2) {
						url = 'selling';
						// url = 'vin_sp';
						this.tabbarActive = -1;
					} else if (index == 3) {
						url = 'column';
					} else if (index == 4) {
						url = 'userMenu';
					}

					if (index == 1 || index == 2) {
						api.openWin({
							name: url,
							url: url + '.html',
							reload: true,
							slidBackEnabled: false,
							pageParam: {
								historyData: null
							}
						})
					}else {
						api.openFrame({
							name: url,
							url: url + '.html',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight - 61 - api.safeArea.bottom
							}
						});
					}


				}
			}
		})
	};
</script>

</html>